<template>
  <view class="withdraw-container">
    <!-- 导航栏 -->
    <up-navbar :border="false" autoBack bgColor="#fff" :title="useT('提现')" titleColor="#333" placeholder />

    <!-- 页面内容 -->
    <view class="content">
      <!-- 总金额卡片 -->
      <view class="info-card">
        <view class="card-label">{{ useT('总金额') }}</view>
        <view class="card-value">
          <text class="value-text">{{ totalAmount }}</text>
          <text class="currency-text">USDT</text>
        </view>
      </view>

      <!-- 输入提现金额 -->
      <view class="input-card">
        <view class="input-label">{{ useT('输入提现金额') }}</view>
        <view class="input-wrapper">
          <input class="amount-input" type="digit" :placeholder="useT('输入提现金额')" v-model="withdrawAmount" @input="onAmountInput" placeholder-class="input-placeholder" />
          <text class="currency-suffix">USDT</text>
        </view>
        <view class="input-tip">
          <text class="tip-text">{{ useT('最小提现金额') }}：{{ minWithdrawAmount }} USDT</text>
          <text class="tip-text" v-if="maxWithdrawAmount">，{{ useT('最大提现金额') }}：{{ maxWithdrawAmount }} USDT</text>
        </view>
      </view>
      <!-- 提现手续费卡片 -->
      <view class="info-card">
        <view class="card-label">{{ useT('提现手续费') }}</view>
        <view class="card-value">
          <text class="value-text">{{ calculatedFeeAmount }}</text>
          <text class="currency-text">USDT</text>
        </view>
        <view class="fee-rate-tip">
          <text class="tip-text">{{ useT('手续费率') }}：{{ feeRate }}%</text>
        </view>
      </view>
      <!-- 提现钱包地址 -->
      <view class="input-card">
        <view class="input-label">{{ useT('提现钱包地址') }}</view>
        <view class="address-select-wrapper" v-if="walletAddressHistory.length > 0">
          <view class="history-address-btn" @click="showAddressPicker = true">
            <text class="history-btn-text">{{ useT('选择历史地址') }}</text>
            <up-icon name="arrow-down" size="14" color="#12c284" />
          </view>
        </view>
        <view class="input-wrapper">
          <input class="address-input" type="text" :placeholder="useT('请输入钱包地址')" v-model="walletAddress" @blur="onAddressBlur" placeholder-class="input-placeholder" />
        </view>
      </view>

      <!-- 历史地址弹窗 -->
      <up-popup :show="showAddressPicker" mode="bottom" :round="20" :closeable="true" :safeAreaInsetBottom="true" @close="showAddressPicker = false">
        <view class="address-popup">
          <view class="popup-header">
            <text class="popup-title">{{ useT('选择历史地址') }}</text>
          </view>
          <view class="address-list">
            <view class="address-item" v-for="(item, index) in walletAddressHistory" :key="index">
              <view class="address-content" @click="onAddressSelect(item)">
                <text class="address-text">{{ item.label }}</text>
              </view>
              <view class="address-actions">
                <view class="delete-btn" @click.stop="deleteAddress(item.address)">
                  <up-icon name="trash" size="18" color="#ff4757" />
                </view>
              </view>
            </view>
            <view class="empty-tip" v-if="walletAddressHistory.length === 0">
              <text class="empty-text">{{ useT('暂无历史地址') }}</text>
            </view>
          </view>
        </view>
      </up-popup>

      <!-- 实际到账金额 -->
      <view class="info-card highlight">
        <view class="card-label">{{ useT('实际到账金额') }}</view>
        <view class="card-value">
          <text class="value-text highlight-text">{{ actualAmount }}</text>
          <text class="currency-text">USDT</text>
        </view>
      </view>

      <!-- 备注 -->
      <view class="input-card">
        <view class="input-label">{{ useT('备注') }}</view>
        <view class="textarea-wrapper">
          <textarea class="remark-textarea" :placeholder="useT('请输入备注（选填）')" v-model="remark" :maxlength="200" placeholder-class="input-placeholder" />
        </view>
      </view>
    </view>

    <!-- 提交按钮 - 固定在底部 -->
    <view class="submit-section">
      <button class="submit-btn" :disabled="!canSubmit" :class="{ disabled: !canSubmit }" @click="handleSubmit">
        <text class="submit-text">{{ useT('提交') }}</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { getWithdrawApplyData, submitWithdraw } from '@/api/user';
import { useUserStore } from '@/stores/user';
import { useT } from '@/utils/i18n';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { computed, nextTick, ref } from 'vue';

const userStore = useUserStore();

// 页面显示时隐藏tabbar
onShow(() => {
  uni.hideTabBar();
});

// 响应式数据
const totalAmount = ref('0.00'); // 总金额（接口获取）
const feeRate = ref('0'); // 提现手续费百分比（接口获取）
const minWithdrawAmount = ref('1'); // 最小提现金额（接口获取）
const maxWithdrawAmount = ref('1000'); // 最大提现金额（接口获取）
const withdrawAmount = ref(''); // 提现金额
const walletAddress = ref(''); // 钱包地址
const remark = ref(''); // 备注
const walletAddressHistory = ref([]); // 历史钱包地址列表
const showAddressPicker = ref(false); // 显示地址选择器

// 获取总金额和手续费
const fetchWithdrawInfo = async () => {
  try {
    const res = await getWithdrawApplyData();
    totalAmount.value = res.data.now_money || '0.00';
    feeRate.value = res.data.withdrawal_fee || '0'; // 手续费百分比
    minWithdrawAmount.value = res.data.user_extract_min_price || '1';
    maxWithdrawAmount.value = res.data.user_extract_max_price || '1000';
  } catch (error) {
    console.error('获取提现信息失败:', error);
  }
};

// 金额输入处理
const onAmountInput = (e) => {
  let value = e.detail.value;

  // 只允许数字和小数点
  value = value.replace(/[^\d.]/g, '');

  // 检测小数位数，如果超过2位就截断
  if (value.includes('.')) {
    const dotIndex = value.indexOf('.');
    const integerPart = value.substring(0, dotIndex);
    const decimalPart = value.substring(dotIndex + 1);

    // 移除小数部分中的其他小数点
    const cleanDecimal = decimalPart.replace(/\./g, '');

    // 如果小数位数超过2位，截断到2位
    if (cleanDecimal.length > 2) {
      value = `${integerPart}.${cleanDecimal.substring(0, 2)}`;
    } else {
      value = `${integerPart}.${cleanDecimal}`;
    }
  }

  // 使用 nextTick 确保值更新后重新渲染
  nextTick(() => {
    withdrawAmount.value = value;
  });
};

// 计算手续费（根据输入金额和手续费百分比）
const calculatedFeeAmount = computed(() => {
  const amount = parseFloat(withdrawAmount.value) || 0;
  const rate = parseFloat(feeRate.value) || 0;
  if (amount <= 0 || rate <= 0) {
    return '0.00';
  }
  const fee = (amount * rate) / 100; // 手续费 = 金额 * 百分比 / 100
  return fee.toFixed(2);
});

// 计算实际到账金额
const actualAmount = computed(() => {
  const amount = parseFloat(withdrawAmount.value) || 0;
  const fee = parseFloat(calculatedFeeAmount.value) || 0;
  const result = amount - fee;
  return result > 0 ? result.toFixed(2) : '0.00';
});

// 判断是否可以提交
const canSubmit = computed(() => {
  const amount = parseFloat(withdrawAmount.value) || 0;
  const total = parseFloat(totalAmount.value) || 0;
  const minAmount = parseFloat(minWithdrawAmount.value) || 1;
  const maxAmount = parseFloat(maxWithdrawAmount.value) || 1000;

  return amount >= minAmount && amount <= Math.min(total, maxAmount) && walletAddress.value.trim().length > 0 && walletAddress.value.trim().length >= 20; // 钱包地址最小长度
});

// 获取存储key
const getStorageKey = () => {
  const uid = userStore.userInfo?.uid;
  if (!uid) {
    return null;
  }
  return `wallet_addresses_${uid}`;
};

// 保存钱包地址到历史记录
const saveWalletAddress = (address) => {
  const key = getStorageKey();
  if (!key || !address || address.trim().length < 20) {
    return;
  }

  const trimmedAddress = address.trim();
  let history = [];

  try {
    const stored = uni.getStorageSync(key);
    if (stored) {
      history = JSON.parse(stored);
    }
  } catch (error) {
    console.error('读取历史地址失败:', error);
    history = [];
  }

  // 去重：移除已存在的相同地址
  history = history.filter((item) => item.address !== trimmedAddress);

  // 将新地址添加到最前面
  history.unshift({
    address: trimmedAddress,
    timestamp: Date.now()
  });

  // 最多保存10个地址
  if (history.length > 10) {
    history = history.slice(0, 10);
  }

  try {
    uni.setStorageSync(key, JSON.stringify(history));
    // 更新历史地址列表
    walletAddressHistory.value = history.map((item) => ({
      address: item.address,
      label: item.address.length > 20 ? `${item.address.substring(0, 10)}...${item.address.substring(item.address.length - 10)}` : item.address
    }));
  } catch (error) {
    console.error('保存历史地址失败:', error);
  }
};

// 加载历史钱包地址
const loadWalletAddressHistory = () => {
  const key = getStorageKey();
  if (!key) {
    return;
  }

  try {
    const stored = uni.getStorageSync(key);
    if (stored) {
      const history = JSON.parse(stored);
      walletAddressHistory.value = history.map((item) => ({
        address: item.address,
        label: item.address.length > 20 ? `${item.address.substring(0, 10)}...${item.address.substring(item.address.length - 10)}` : item.address
      }));

      // 如果有历史地址，自动填充第一个
      if (history.length > 0 && !walletAddress.value) {
        walletAddress.value = history[0].address;
      }
    }
  } catch (error) {
    console.error('加载历史地址失败:', error);
    walletAddressHistory.value = [];
  }
};

// 地址输入失焦时保存
const onAddressBlur = () => {
  if (walletAddress.value && walletAddress.value.trim().length >= 20) {
    saveWalletAddress(walletAddress.value);
  }
};

// 选择历史地址
const onAddressSelect = (item) => {
  if (item && item.address) {
    walletAddress.value = item.address;
  }
  showAddressPicker.value = false;
};

// 删除历史地址
const deleteAddress = (address) => {
  showAddressPicker.value = false;
  uni.showModal({
    title: useT('提示'),
    content: useT('确定要删除这个地址吗？'),
    confirmText: useT('删除'),
    cancelText: useT('取消'),
    confirmColor: '#ff4757',
    success: (res) => {
      if (res.confirm) {
        const key = getStorageKey();
        if (!key) {
          return;
        }

        try {
          const stored = uni.getStorageSync(key);
          if (stored) {
            let history = JSON.parse(stored);
            // 从历史记录中移除该地址
            history = history.filter((item) => item.address !== address);
            // 保存更新后的历史记录
            uni.setStorageSync(key, JSON.stringify(history));
            // 更新历史地址列表
            walletAddressHistory.value = history.map((item) => ({
              address: item.address,
              label: item.address.length > 20 ? `${item.address.substring(0, 10)}...${item.address.substring(item.address.length - 10)}` : item.address
            }));

            uni.showToast({
              title: useT('删除成功'),
              icon: 'success'
            });
          }
        } catch (error) {
          console.error('删除历史地址失败:', error);
          uni.showToast({
            title: useT('删除失败'),
            icon: 'none'
          });
        }
        setTimeout(() => {
          showAddressPicker.value = true;
        }, 100);
      }
    }
  });
};

// 提交提现
const handleSubmit = async () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: useT('请填写完整信息'),
      icon: 'none'
    });
    return;
  }

  // 验证钱包地址格式（简单验证）
  if (walletAddress.value.trim().length < 20) {
    uni.showToast({
      title: useT('钱包地址格式不正确'),
      icon: 'none'
    });
    return;
  }

  // 保存钱包地址到历史记录
  saveWalletAddress(walletAddress.value);

  // 验证提现金额
  const amount = parseFloat(withdrawAmount.value);
  const total = parseFloat(totalAmount.value);
  const minAmount = parseFloat(minWithdrawAmount.value) || 1;
  const maxAmount = parseFloat(maxWithdrawAmount.value) || 1000;
  const actualMaxAmount = Math.min(total, maxAmount);

  if (amount < minAmount) {
    uni.showToast({
      title: `${useT('提现金额不能小于')} ${minAmount} USDT`,
      icon: 'none'
    });
    return;
  }

  if (amount > actualMaxAmount) {
    uni.showToast({
      title: `${useT('提现金额不能大于')} ${actualMaxAmount} USDT`,
      icon: 'none'
    });
    return;
  }

  // 显示加载提示
  uni.showLoading({
    title: useT('提交中..'),
    mask: true
  });

  try {
    const res = await submitWithdraw({
      money: withdrawAmount.value,
      Address: walletAddress.value,
      extract_type: 4,
      make: remark.value || ''
    });

    if (res.status === 200) {
      uni.hideLoading();
      uni.showToast({
        title: useT('提交成功'),
        icon: 'success',
        duration: 2000
      });

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 2000);
    } else {
      uni.hideLoading();
      uni.showToast({
        title: res.msg || useT('提交失败，请重试'),
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('提交提现失败:', error);
    uni.showToast({
      title: useT('提交失败，请重试'),
      icon: 'none'
    });
  }
};

// 页面加载
onLoad(() => {
  fetchWithdrawInfo();
  loadWalletAddressHistory();
});
</script>

<style lang="scss" scoped>
.withdraw-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding: 32rpx;
  padding-bottom: 180rpx; // 为底部固定按钮留出空间
}

// 信息卡片
.info-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  &.highlight {
    background: linear-gradient(135deg, #e8f8f3 0%, #d0f0e4 100%);
    border: 2rpx solid #12c284;
  }

  .card-label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 16rpx;
  }

  .card-value {
    display: flex;
    align-items: baseline;

    .value-text {
      font-size: 48rpx;
      font-weight: 700;
      color: #333;
      margin-right: 12rpx;

      &.highlight-text {
        color: #12c284;
      }
    }

    .currency-text {
      font-size: 28rpx;
      color: #999;
      font-weight: 500;
    }
  }

  .fee-rate-tip {
    margin-top: 12rpx;

    .tip-text {
      font-size: 24rpx;
      color: #999;
    }
  }
}

// 输入卡片
.input-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .input-label {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 20rpx;
  }
  .input-placeholder {
    font-size: 28rpx;
  }

  .address-select-wrapper {
    margin-bottom: 16rpx;

    .history-address-btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #f0f9f6;
      border: 2rpx solid #12c284;
      border-radius: 12rpx;
      padding: 16rpx 24rpx;
      margin-bottom: 16rpx;

      .history-btn-text {
        font-size: 26rpx;
        color: #12c284;
        font-weight: 500;
      }
    }
  }

  .input-wrapper {
    display: flex;
    align-items: center;
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 24rpx;
    border: 2rpx solid #e0e0e0;
    transition: all 0.3s ease;

    &:focus-within {
      border-color: #12c284;
      background: #fff;
    }

    .amount-input {
      flex: 1;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      background: transparent;
    }

    .address-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      background: transparent;
    }

    .currency-suffix {
      font-size: 28rpx;
      color: #12c284;
      font-weight: 600;
      margin-left: 12rpx;
    }
  }

  .input-placeholder {
    color: #d0d0d0;
  }

  .input-tip {
    margin-top: 12rpx;

    .tip-text {
      font-size: 24rpx;
      color: #999;
    }
  }

  .textarea-wrapper {
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 24rpx;
    border: 2rpx solid #e0e0e0;
    transition: all 0.3s ease;

    &:focus-within {
      border-color: #12c284;
      background: #fff;
    }

    .remark-textarea {
      width: 100%;
      min-height: 120rpx;
      font-size: 28rpx;
      color: #333;
      background: transparent;
      line-height: 1.6;
    }
  }
}

// 历史地址弹窗样式
.address-popup {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 70vh;
  display: flex;
  flex-direction: column;
  padding-bottom: 40rpx;

  .popup-header {
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
    text-align: center;

    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }

  .address-list {
    flex: 1;
    overflow-y: auto;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));

    .address-item {
      display: flex;
      align-items: center;
      background: #f8f9fa;
      border-radius: 12rpx;
      padding: 24rpx;
      margin-bottom: 16rpx;
      border: 2rpx solid #e0e0e0;
      transition: all 0.3s ease;

      &:active {
        background: #f0f0f0;
      }

      &:last-child {
        margin-bottom: 0;
      }

      .address-content {
        flex: 1;
        padding-right: 16rpx;

        .address-text {
          font-size: 28rpx;
          color: #333;
          word-break: break-all;
          line-height: 1.5;
        }
      }

      .address-actions {
        display: flex;
        align-items: center;

        .delete-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 64rpx;
          height: 64rpx;
          background: #fff5f5;
          border-radius: 8rpx;
          transition: all 0.3s ease;

          &:active {
            background: #ffe5e5;
            transform: scale(0.95);
          }
        }
      }
    }

    .empty-tip {
      padding: 80rpx 0;
      text-align: center;

      .empty-text {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}

// 提交按钮区域 - 固定在底部
.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 100;

  .submit-btn {
    width: 100%;
    height: 96rpx;
    background: linear-gradient(135deg, #4a90e2 0%, #12c284 100%);
    border-radius: 24rpx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 16rpx rgba(18, 194, 132, 0.3);
    transition: all 0.3s ease;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(18, 194, 132, 0.3);
    }

    &.disabled {
      background: #e0e0e0;
      box-shadow: none;
      opacity: 0.6;

      &:active {
        transform: none;
      }
    }

    .submit-text {
      font-size: 32rpx;
      font-weight: 600;
      color: #fff;
    }
  }
}
</style>
